package framework.jackson.custom;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 对指定的 @JsonFilter 临时调整序列化格式
 */
public class JsonFilterTest {
    private static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {
        Obj.InnerObj innerObj = new Obj.InnerObj("value_g", "value_h");
        Obj obj = new Obj("value_a", innerObj, "value_c");

        SimpleFilterProvider filterProvider = new SimpleFilterProvider();
        filterProvider.addFilter("dynamicFilter", SimpleBeanPropertyFilter.serializeAllExcept("g"));
        String result = mapper.writer(filterProvider).writeValueAsString(obj);

        // {"a":"value_a","b":{"h":"value_h"},"c":"value_c"}
        System.out.println(result);
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Obj {
        private String a;
        private InnerObj b;
        private String c;

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        @JsonFilter("dynamicFilter")
        public static class InnerObj {
            private String g;
            private String h;
        }
    }

}
